package com.github.winyiwin.matrix.dubbo.swagger2.provider;

import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.DocumentationCache;
import springfox.documentation.swagger.web.InMemorySwaggerResourcesProvider;
import springfox.documentation.swagger.web.SwaggerResource;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Primary
@Component
public class DefaultSwaggerResourcesProvider extends InMemorySwaggerResourcesProvider {

    public DefaultSwaggerResourcesProvider(Environment environment, DocumentationCache documentationCache) {
        super(environment, documentationCache);
    }

    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> swaggerResources = super.get();
        swaggerResources.forEach(swaggerResource -> {
                    String name = swaggerResource.getName();
                    if (SwaggerConfigEnum.SwaggerConfigMap.containsKey(name)) {
                        swaggerResource.setLocation(SwaggerConfigEnum.SwaggerConfigMap.get(name).getLocation());
                    }
                }
        );
        return swaggerResources;
    }

    private enum SwaggerConfigEnum {
        DUBBO("dubbo", "/swagger-dubbo/api-docs");
        private String name;
        private String location;
        private final static Map<String, SwaggerConfigEnum> SwaggerConfigMap = Arrays.stream(SwaggerConfigEnum.values()).collect(Collectors.toMap(SwaggerConfigEnum::getName, Function.identity()));

        SwaggerConfigEnum(String name, String location) {
            this.name = name;
            this.location = location;
        }

        public String getName() {
            return name;
        }

        public String getLocation() {
            return location;
        }
    }


}
